<?php
class AgendasController extends AppController {

	var $name = 'Agendas';
	var $uses = array('ClientsUser','User','Agenda','Sucursal','AgendasSegment','SucursalsUser');
	
    function beforeFilter () {
        parent::beforeFilter();

		// Aplico el Layout segun la Vista o si es AJAX
		if ($this->RequestHandler->isAjax()) {
			$this->layout = 'ajax';
		}else{
			// Cambio la Vista por la del Rol
			$this->layout = strtolower($this->Session->read('VistaActual'));
		}
    }

	function index() {
	
		$client_id = $this->Session->read('ClientesUsuarioLogueado.id');
	
		$this->Agenda->recursive = 0;
	
		$agendas = $this->Agenda->query("
			SELECT 
				User.id, User.lastname, User.name, Agenda.id, Agenda.sucursal_id, Agenda.nombre, Sucursal.name
			FROM 
				users AS User 
				INNER JOIN clients_users AS ClientsUsers ON ClientsUsers.user_id = User.id
				LEFT JOIN agendas AS Agenda ON (Agenda.user_id = User.id AND Agenda.client_id = ClientsUsers.client_id)
				LEFT JOIN sucursals AS Sucursal ON (Agenda.sucursal_id = Sucursal.id AND Agenda.client_id = Sucursal.client_id)
			WHERE
				ClientsUsers.client_id = '$client_id' AND ClientsUsers.staterecord_id = 1 AND Agenda.staterecord_id = 1
			ORDER BY 
				User.lastname, User.name
			;"
		);

		
//pr($agendas);		
		
		$segmentos = $this->Agenda->query("
			SELECT 
				Agenda.id, Agenda.user_id, Agenda.sucursal_id, Agenda.nombre, Segment.id, Segment.day_id, Segment.horario_desde, 
				Segment.horario_hasta, Segment.duracion, 
				Segment.sobreturno, Segment.edad_desde, Segment.edad_hasta, Segment.sexo, Segment.max_sobreturnos, Segment.sobreturnos_publicos
			FROM 
				agendas AS Agenda
				INNER JOIN agendas_segments AS AgendasSegment ON Agenda.id = AgendasSegment.agenda_id
				INNER JOIN segments AS Segment ON Segment.id = AgendasSegment.segment_id
			WHERE
				Agenda.client_id = '$client_id'
			ORDER BY
				Agenda.user_id, Segment.day_id, Segment.horario_desde
			;"
		);
//pr($segmentos);
		$this->set(compact('agendas','segmentos'));
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid agenda', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('agenda', $this->Agenda->read(null, $id));
	}

	function add($id_usuario = null) {
		
		$client_id = $this->Session->read('ClientesUsuarioLogueado.id');
		$this->set('client_id', $client_id);
		
		if (!empty($this->data)){
			$this->Agenda->create();

			// Creo la Agenda
			$this->Agenda->save($this->data['Agenda']);

			//-------------------- Existe en sucursals_user ???
			$Existe = $this->SucursalsUser->find('first',array(
												'conditions'=>array(
													'SucursalsUser.sucursal_id'=>$this->data['Agenda']['sucursal_id'],
													'SucursalsUser.user_id'=>$this->data['Agenda']['user_id'],
													'SucursalsUser.client_id'=>$this->data['Agenda']['client_id'],
												)
												));
			if(!$Existe){
				$su['id'] = 0;
				$su['sucursal_id'] = $this->data['Agenda']['sucursal_id'];
				$su['user_id'] = $this->data['Agenda']['user_id'];
				$su['client_id'] = $this->data['Agenda']['client_id'];
				$this->SucursalsUser->create();
				$this->SucursalsUser->save($su);
			
			}
			
			$this->redirect('/clients/view/'.$this->Session->read('ClientesUsuarioLogueado.id').'/3');
		}
		
		//-----------------------------------------------------------
		// Obtiene las sucursales de ese cliente
		//-----------------------------------------------------------
		$x = $this->Sucursal->find('all', array(
												'conditions' => array('Sucursal.client_id' => $client_id)
											) );
		$Sucursales = array();	
		foreach($x as $clave=>$z){
			$id     = $z['Sucursal']['id'];
			$nombre = $z['Sucursal']['name'];
			$Sucursales[$id] = $nombre;
		}
		$this->set('Sucursales', $Sucursales);

		
		//-----------------------------------------------------------
		// Obtiene los usuarios de ese cliente
		//-----------------------------------------------------------
		$x = $this->ClientsUser->find('all', array(
						'conditions' => array(
											'ClientsUser.client_id' => $client_id,
											'NOT' => array ('ClientsUser.staterecord_id' => array('2','3'))
										),
						'fields' => array('ClientsUser.id','User.id', 'User.name','User.lastname','Client.id','User.last_login'),
						'order' => array('User.lastname','User.name'),
		) );
		$Usuarios = array();
		foreach($x as $clave=>$z){
			$id     = $z['User']['id'];
			$nombre = $z['User']['lastname'].', '.$z['User']['name'];
			$Usuarios[$id] = $nombre;
		}
		$this->set('Usuarios', $Usuarios);
		
		$this->set('agenda_id', 0);
		
	}

	function edit($id = null) {
		$client_id = $this->Session->read('ClientesUsuarioLogueado.id');
		$this->set('client_id', $client_id);
		
		if (!empty($this->data)){

			$this->Agenda->save($this->data['Agenda']);

			$this->redirect('/clients/view/'.$this->Session->read('ClientesUsuarioLogueado.id').'/3');
		}


		//-----------------------------------------------------------
		// Obtiene la Agenda
		//-----------------------------------------------------------
		$this->Agenda->recursive = 0;
		$Agenda = $this->Agenda->read(null,$id );

		
		//-----------------------------------------------------------
		// Obtiene la Sucursal
		//-----------------------------------------------------------
		$this->Sucursal->recursive = 0;
		$Sucursal = $this->Sucursal->read(null, $Agenda['Agenda']['sucursal_id']);

		//-----------------------------------------------------------
		// Obtiene el Usuario
		//-----------------------------------------------------------
		$this->User->recursive = 0;
		$Usuario = $this->User->read(null, $Agenda['Agenda']['user_id']);

		$this->set('Agenda',$Agenda);
		$this->set('Sucursal',$Sucursal);
		$this->set('Usuario',$Usuario);
		
	}
	
	
	function delete($agenda_id=0) {
	
		$client_id = $this->Session->read('ClientesUsuarioLogueado.id');

		$sql = "update agendas set staterecord_id='2' where client_id='$client_id' and id='$agenda_id'";
		if ( $this->Agenda->query($sql) ) {
			$this->Session->setFlash(__('La Agenda ha sido eliminada', true));
		} else {
			$this->Session->setFlash(__('La Agenda no se pudo borrar', true));
		}
		$this->redirect("/clients/view/$client_id/3");
		die();	
	}
	
	
}
?>